# 创建营销管理主页面
<template>
  <div class="marketing-management">
    <!-- 统计卡片 -->
    <el-row :gutter="20" class="statistics-cards">
      <el-col :span="24" class="mb-4">
        <el-button type="primary" @click="handleViewStatistics">
          <el-icon><DataAnalysis /></el-icon>
          查看营销统计
        </el-button>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>活动总数</span>
            </div>
          </template>
          <div class="card-content">
            <div class="amount">{{ statistics.totalPromotions }}</div>
            <div class="trend">
              较上月
              <span :class="statistics.promotionTrend >= 0 ? 'up' : 'down'">
                {{ Math.abs(statistics.promotionTrend) }}%
                <el-icon>
                  <component :is="statistics.promotionTrend >= 0 ? 'ArrowUp' : 'ArrowDown'" />
                </el-icon>
              </span>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>优惠券总数</span>
            </div>
          </template>
          <div class="card-content">
            <div class="amount">{{ statistics.totalCoupons }}</div>
            <div class="percentage">
              使用率 {{ statistics.couponUsageRate }}%
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>营销转化率</span>
            </div>
          </template>
          <div class="card-content">
            <div class="amount">{{ statistics.conversionRate }}%</div>
            <div class="trend">
              较上月
              <span :class="statistics.conversionTrend >= 0 ? 'up' : 'down'">
                {{ Math.abs(statistics.conversionTrend) }}%
                <el-icon>
                  <component :is="statistics.conversionTrend >= 0 ? 'ArrowUp' : 'ArrowDown'" />
                </el-icon>
              </span>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>营销销售额</span>
            </div>
          </template>
          <div class="card-content">
            <div class="amount">¥{{ statistics.totalSales }}</div>
            <div class="trend">
              较上月
              <span :class="statistics.salesTrend >= 0 ? 'up' : 'down'">
                {{ Math.abs(statistics.salesTrend) }}%
                <el-icon>
                  <component :is="statistics.salesTrend >= 0 ? 'ArrowUp' : 'ArrowDown'" />
                </el-icon>
              </span>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 营销活动管理 -->
    <el-card class="promotion-card">
      <template #header>
        <div class="card-header">
          <span>营销活动</span>
          <el-button type="primary" @click="handleAddPromotion">创建活动</el-button>
        </div>
      </template>
      <el-table :data="promotionList" border style="width: 100%">
        <el-table-column prop="name" label="活动名称" min-width="150" />
        <el-table-column prop="type" label="活动类型" width="120">
          <template #default="{ row }">
            <el-tag :type="getPromotionTypeTag(row.type)">
              {{ getPromotionTypeName(row.type) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="startTime" label="开始时间" width="180" />
        <el-table-column prop="endTime" label="结束时间" width="180" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getPromotionStatusTag(row.status)">
              {{ getPromotionStatusName(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="participants" label="参与人数" width="100" />
        <el-table-column prop="conversionRate" label="转化率" width="100">
          <template #default="{ row }">
            {{ row.conversionRate }}%
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleEditPromotion(row)">
              编辑
            </el-button>
            <el-button type="success" link @click="handleViewPromotionDetail(row)">
              详情
            </el-button>
            <el-button 
              type="danger" 
              link 
              @click="handleDeletePromotion(row)"
              :disabled="row.status === 'running'"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="promotionPage.current"
          v-model:page-size="promotionPage.size"
          :total="promotionPage.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handlePromotionSizeChange"
          @current-change="handlePromotionCurrentChange"
        />
      </div>
    </el-card>

    <!-- 优惠券管理 -->
    <el-card class="coupon-card">
      <template #header>
        <div class="card-header">
          <span>优惠券</span>
          <el-button type="primary" @click="handleAddCoupon">创建优惠券</el-button>
        </div>
      </template>
      <el-table :data="couponList" border style="width: 100%">
        <el-table-column prop="name" label="优惠券名称" min-width="150" />
        <el-table-column prop="type" label="优惠类型" width="120">
          <template #default="{ row }">
            <el-tag :type="getCouponTypeTag(row.type)">
              {{ getCouponTypeName(row.type) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="value" label="优惠金额/折扣" width="120">
          <template #default="{ row }">
            {{ row.type === 'discount' ? row.value + '折' : '¥' + row.value }}
          </template>
        </el-table-column>
        <el-table-column prop="minAmount" label="使用门槛" width="120">
          <template #default="{ row }">
            ¥{{ row.minAmount }}
          </template>
        </el-table-column>
        <el-table-column prop="startTime" label="有效期开始" width="180" />
        <el-table-column prop="endTime" label="有效期结束" width="180" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getCouponStatusTag(row.status)">
              {{ getCouponStatusName(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="usageCount" label="已使用" width="100" />
        <el-table-column prop="totalCount" label="发放数量" width="100" />
        <el-table-column label="操作" width="250" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleEditCoupon(row)">
              编辑
            </el-button>
            <el-button type="success" link @click="handleIssueCoupon(row)">
              发放
            </el-button>
            <el-button type="warning" link @click="handleViewCouponDetail(row)">
              详情
            </el-button>
            <el-button 
              type="danger" 
              link 
              @click="handleDeleteCoupon(row)"
              :disabled="row.status === 'active'"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="couponPage.current"
          v-model:page-size="couponPage.size"
          :total="couponPage.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleCouponSizeChange"
          @current-change="handleCouponCurrentChange"
        />
      </div>
    </el-card>

    <!-- 活动表单对话框 -->
    <el-dialog
      v-model="promotionDialogVisible"
      :title="promotionForm.id ? '编辑活动' : '创建活动'"
      width="600px"
    >
      <el-form
        ref="promotionFormRef"
        :model="promotionForm"
        :rules="promotionFormRules"
        label-width="100px"
      >
        <el-form-item label="活动名称" prop="name">
          <el-input v-model="promotionForm.name" placeholder="请输入活动名称" />
        </el-form-item>
        <el-form-item label="活动类型" prop="type">
          <el-select v-model="promotionForm.type" placeholder="请选择活动类型">
            <el-option label="满减活动" value="discount" />
            <el-option label="秒杀活动" value="seckill" />
            <el-option label="拼团活动" value="group" />
            <el-option label="新人专享" value="new_user" />
          </el-select>
        </el-form-item>
        <el-form-item label="活动时间" prop="time">
          <el-date-picker
            v-model="promotionForm.time"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>
        <el-form-item label="活动规则" prop="rules">
          <el-input
            v-model="promotionForm.rules"
            type="textarea"
            :rows="4"
            placeholder="请输入活动规则"
          />
        </el-form-item>
        <el-form-item label="活动商品" prop="products">
          <el-select
            v-model="promotionForm.products"
            multiple
            filterable
            placeholder="请选择活动商品"
          >
            <el-option
              v-for="product in productOptions"
              :key="product.id"
              :label="product.name"
              :value="product.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="活动状态" prop="status">
          <el-radio-group v-model="promotionForm.status">
            <el-radio label="draft">草稿</el-radio>
            <el-radio label="pending">待开始</el-radio>
            <el-radio label="running">进行中</el-radio>
            <el-radio label="ended">已结束</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="promotionDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handlePromotionSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 优惠券表单对话框 -->
    <el-dialog
      v-model="couponDialogVisible"
      :title="couponForm.id ? '编辑优惠券' : '创建优惠券'"
      width="500px"
    >
      <el-form
        ref="couponFormRef"
        :model="couponForm"
        :rules="couponFormRules"
        label-width="100px"
      >
        <el-form-item label="优惠券名称" prop="name">
          <el-input v-model="couponForm.name" placeholder="请输入优惠券名称" />
        </el-form-item>
        <el-form-item label="优惠类型" prop="type">
          <el-radio-group v-model="couponForm.type">
            <el-radio label="amount">满减券</el-radio>
            <el-radio label="discount">折扣券</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="优惠金额" prop="value" v-if="couponForm.type === 'amount'">
          <el-input-number
            v-model="couponForm.value"
            :min="0"
            :precision="2"
            :step="10"
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="折扣比例" prop="value" v-else>
          <el-input-number
            v-model="couponForm.value"
            :min="0"
            :max="10"
            :precision="1"
            :step="0.1"
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="使用门槛" prop="minAmount">
          <el-input-number
            v-model="couponForm.minAmount"
            :min="0"
            :precision="2"
            :step="10"
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="有效期" prop="time">
          <el-date-picker
            v-model="couponForm.time"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>
        <el-form-item label="发放数量" prop="totalCount">
          <el-input-number
            v-model="couponForm.totalCount"
            :min="1"
            :precision="0"
            :step="100"
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="使用说明" prop="description">
          <el-input
            v-model="couponForm.description"
            type="textarea"
            :rows="3"
            placeholder="请输入使用说明"
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="couponForm.status">
            <el-radio label="draft">草稿</el-radio>
            <el-radio label="active">已启用</el-radio>
            <el-radio label="inactive">已停用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="couponDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleCouponSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 发放优惠券对话框 -->
    <el-dialog
      v-model="issueDialogVisible"
      title="发放优惠券"
      width="500px"
    >
      <el-form
        ref="issueFormRef"
        :model="issueForm"
        :rules="issueFormRules"
        label-width="100px"
      >
        <el-form-item label="发放方式" prop="type">
          <el-radio-group v-model="issueForm.type">
            <el-radio label="all">全部会员</el-radio>
            <el-radio label="level">指定等级</el-radio>
            <el-radio label="tag">指定标签</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="会员等级" prop="levelIds" v-if="issueForm.type === 'level'">
          <el-select
            v-model="issueForm.levelIds"
            multiple
            placeholder="请选择会员等级"
          >
            <el-option
              v-for="level in levelOptions"
              :key="level.id"
              :label="level.name"
              :value="level.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="会员标签" prop="tagIds" v-if="issueForm.type === 'tag'">
          <el-select
            v-model="issueForm.tagIds"
            multiple
            placeholder="请选择会员标签"
          >
            <el-option
              v-for="tag in tagOptions"
              :key="tag.id"
              :label="tag.name"
              :value="tag.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="发放数量" prop="count">
          <el-input-number
            v-model="issueForm.count"
            :min="1"
            :precision="0"
            :step="100"
            style="width: 200px"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="issueDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleIssueSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ArrowUp, ArrowDown, DataAnalysis } from '@element-plus/icons-vue'
import {
  getMerchantPromotionEffect,
  getMerchantPromotions,
  createMerchantPromotion,
  updateMerchantPromotion,
  deleteMerchantPromotion,
  getMerchantCouponList,
  createMerchantCoupon,
  updateMerchantCoupon,
  deleteMerchantCoupon,
  issueMerchantCoupon,
  batchIssueMerchantCoupons,
  getMerchantMemberLevelList,
  getMerchantMemberTagList
} from '@/api/merchant'

const router = useRouter()

// 统计数据
const statistics = reactive({
  totalPromotions: 0,
  promotionTrend: 0,
  totalCoupons: 0,
  couponUsageRate: 0,
  conversionRate: 0,
  conversionTrend: 0,
  totalSales: 0,
  salesTrend: 0
})

// 活动列表
const promotionList = ref([])
const promotionPage = reactive({
  current: 1,
  size: 10,
  total: 0
})

// 优惠券列表
const couponList = ref([])
const couponPage = reactive({
  current: 1,
  size: 10,
  total: 0
})

// 商品选项
const productOptions = ref([])

// 会员等级选项
const levelOptions = ref([])

// 会员标签选项
const tagOptions = ref([])

// 活动表单
const promotionDialogVisible = ref(false)
const promotionFormRef = ref(null)
const promotionForm = reactive({
  id: '',
  name: '',
  type: '',
  time: [],
  rules: '',
  products: [],
  status: 'draft'
})

// 优惠券表单
const couponDialogVisible = ref(false)
const couponFormRef = ref(null)
const couponForm = reactive({
  id: '',
  name: '',
  type: 'amount',
  value: 0,
  minAmount: 0,
  time: [],
  totalCount: 100,
  description: '',
  status: 'draft'
})

// 发放优惠券表单
const issueDialogVisible = ref(false)
const issueFormRef = ref(null)
const issueForm = reactive({
  type: 'all',
  levelIds: [],
  tagIds: [],
  count: 1
})

// 表单验证规则
const promotionFormRules = {
  name: [{ required: true, message: '请输入活动名称', trigger: 'blur' }],
  type: [{ required: true, message: '请选择活动类型', trigger: 'change' }],
  time: [{ required: true, message: '请选择活动时间', trigger: 'change' }],
  rules: [{ required: true, message: '请输入活动规则', trigger: 'blur' }],
  products: [{ required: true, message: '请选择活动商品', trigger: 'change' }],
  status: [{ required: true, message: '请选择活动状态', trigger: 'change' }]
}

const couponFormRules = {
  name: [{ required: true, message: '请输入优惠券名称', trigger: 'blur' }],
  type: [{ required: true, message: '请选择优惠类型', trigger: 'change' }],
  value: [{ required: true, message: '请输入优惠金额/折扣', trigger: 'blur' }],
  minAmount: [{ required: true, message: '请输入使用门槛', trigger: 'blur' }],
  time: [{ required: true, message: '请选择有效期', trigger: 'change' }],
  totalCount: [{ required: true, message: '请输入发放数量', trigger: 'blur' }],
  description: [{ required: true, message: '请输入使用说明', trigger: 'blur' }],
  status: [{ required: true, message: '请选择状态', trigger: 'change' }]
}

const issueFormRules = {
  type: [{ required: true, message: '请选择发放方式', trigger: 'change' }],
  levelIds: [{ required: true, message: '请选择会员等级', trigger: 'change' }],
  tagIds: [{ required: true, message: '请选择会员标签', trigger: 'change' }],
  count: [{ required: true, message: '请输入发放数量', trigger: 'blur' }]
}

// 获取统计数据
const getStatistics = async () => {
  try {
    const { data } = await getMerchantPromotionEffect()
    Object.assign(statistics, data)
  } catch (error) {
    console.error('获取统计数据失败:', error)
    ElMessage.error('获取统计数据失败')
  }
}

// 获取活动列表
const getPromotionList = async () => {
  try {
    const params = {
      page: promotionPage.current,
      size: promotionPage.size
    }
    const { data } = await getMerchantPromotions(params)
    promotionList.value = data.list
    promotionPage.total = data.total
  } catch (error) {
    console.error('获取活动列表失败:', error)
    ElMessage.error('获取活动列表失败')
  }
}

// 获取优惠券列表
const getCouponList = async () => {
  try {
    const params = {
      page: couponPage.current,
      size: couponPage.size
    }
    const { data } = await getMerchantCouponList(params)
    couponList.value = data.list
    couponPage.total = data.total
  } catch (error) {
    console.error('获取优惠券列表失败:', error)
    ElMessage.error('获取优惠券列表失败')
  }
}

// 获取会员等级列表
const getLevelList = async () => {
  try {
    const { data } = await getMerchantMemberLevelList()
    levelOptions.value = data
  } catch (error) {
    console.error('获取会员等级列表失败:', error)
    ElMessage.error('获取会员等级列表失败')
  }
}

// 获取会员标签列表
const getTagList = async () => {
  try {
    const { data } = await getMerchantMemberTagList()
    tagOptions.value = data
  } catch (error) {
    console.error('获取会员标签列表失败:', error)
    ElMessage.error('获取会员标签列表失败')
  }
}

// 活动类型标签
const getPromotionTypeTag = (type) => {
  const map = {
    discount: 'success',
    seckill: 'danger',
    group: 'warning',
    new_user: 'info'
  }
  return map[type] || ''
}

// 活动类型名称
const getPromotionTypeName = (type) => {
  const map = {
    discount: '满减活动',
    seckill: '秒杀活动',
    group: '拼团活动',
    new_user: '新人专享'
  }
  return map[type] || type
}

// 活动状态标签
const getPromotionStatusTag = (status) => {
  const map = {
    draft: 'info',
    pending: 'warning',
    running: 'success',
    ended: ''
  }
  return map[status] || ''
}

// 活动状态名称
const getPromotionStatusName = (status) => {
  const map = {
    draft: '草稿',
    pending: '待开始',
    running: '进行中',
    ended: '已结束'
  }
  return map[status] || status
}

// 优惠券类型标签
const getCouponTypeTag = (type) => {
  const map = {
    amount: 'success',
    discount: 'warning'
  }
  return map[type] || ''
}

// 优惠券类型名称
const getCouponTypeName = (type) => {
  const map = {
    amount: '满减券',
    discount: '折扣券'
  }
  return map[type] || type
}

// 优惠券状态标签
const getCouponStatusTag = (status) => {
  const map = {
    draft: 'info',
    active: 'success',
    inactive: ''
  }
  return map[status] || ''
}

// 优惠券状态名称
const getCouponStatusName = (status) => {
  const map = {
    draft: '草稿',
    active: '已启用',
    inactive: '已停用'
  }
  return map[status] || status
}

// 创建活动
const handleAddPromotion = () => {
  Object.keys(promotionForm).forEach(key => {
    promotionForm[key] = key === 'status' ? 'draft' : 
                        key === 'products' ? [] : 
                        key === 'time' ? [] : ''
  })
  promotionForm.id = ''
  promotionDialogVisible.value = true
}

// 编辑活动
const handleEditPromotion = (row) => {
  Object.assign(promotionForm, row)
  promotionForm.time = [row.startTime, row.endTime]
  promotionDialogVisible.value = true
}

// 删除活动
const handleDeletePromotion = async (row) => {
  if (row.status === 'running') {
    ElMessage.warning('进行中的活动无法删除')
    return
  }
  try {
    await ElMessageBox.confirm('确认删除该活动吗？', '提示', {
      type: 'warning'
    })
    await deleteMerchantPromotion(row.id)
    ElMessage.success('删除成功')
    getPromotionList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除活动失败:', error)
    }
  }
}

// 提交活动表单
const handlePromotionSubmit = async () => {
  if (!promotionFormRef.value) return
  
  try {
    await promotionFormRef.value.validate()
    const [startTime, endTime] = promotionForm.time
    const data = {
      ...promotionForm,
      startTime,
      endTime
    }
    delete data.time
    
    if (promotionForm.id) {
      await updateMerchantPromotion(promotionForm.id, data)
      ElMessage.success('更新成功')
    } else {
      await createMerchantPromotion(data)
      ElMessage.success('创建成功')
    }
    promotionDialogVisible.value = false
    getPromotionList()
  } catch (error) {
    console.error('提交活动失败:', error)
  }
}

// 创建优惠券
const handleAddCoupon = () => {
  Object.keys(couponForm).forEach(key => {
    couponForm[key] = key === 'type' ? 'amount' :
                     key === 'status' ? 'draft' :
                     key === 'time' ? [] :
                     key === 'value' || key === 'minAmount' ? 0 :
                     key === 'totalCount' ? 100 : ''
  })
  couponForm.id = ''
  couponDialogVisible.value = true
}

// 编辑优惠券
const handleEditCoupon = (row) => {
  Object.assign(couponForm, row)
  couponForm.time = [row.startTime, row.endTime]
  couponDialogVisible.value = true
}

// 删除优惠券
const handleDeleteCoupon = async (row) => {
  if (row.status === 'active') {
    ElMessage.warning('已启用的优惠券无法删除')
    return
  }
  try {
    await ElMessageBox.confirm('确认删除该优惠券吗？', '提示', {
      type: 'warning'
    })
    await deleteMerchantCoupon(row.id)
    ElMessage.success('删除成功')
    getCouponList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除优惠券失败:', error)
    }
  }
}

// 提交优惠券表单
const handleCouponSubmit = async () => {
  if (!couponFormRef.value) return
  
  try {
    await couponFormRef.value.validate()
    const [startTime, endTime] = couponForm.time
    const data = {
      ...couponForm,
      startTime,
      endTime
    }
    delete data.time
    
    if (couponForm.id) {
      await updateMerchantCoupon(couponForm.id, data)
      ElMessage.success('更新成功')
    } else {
      await createMerchantCoupon(data)
      ElMessage.success('创建成功')
    }
    couponDialogVisible.value = false
    getCouponList()
  } catch (error) {
    console.error('提交优惠券失败:', error)
  }
}

// 发放优惠券
const handleIssueCoupon = (row) => {
  issueForm.type = 'all'
  issueForm.levelIds = []
  issueForm.tagIds = []
  issueForm.count = 1
  issueForm.couponId = row.id
  issueDialogVisible.value = true
}

// 提交发放优惠券
const handleIssueSubmit = async () => {
  if (!issueFormRef.value) return
  
  try {
    await issueFormRef.value.validate()
    const data = {
      couponId: issueForm.couponId,
      type: issueForm.type,
      count: issueForm.count
    }
    
    if (issueForm.type === 'level') {
      data.levelIds = issueForm.levelIds
    } else if (issueForm.type === 'tag') {
      data.tagIds = issueForm.tagIds
    }
    
    await batchIssueMerchantCoupons(data)
    ElMessage.success('发放成功')
    issueDialogVisible.value = false
    getCouponList()
  } catch (error) {
    console.error('发放优惠券失败:', error)
  }
}

// 查看活动详情
const handleViewPromotionDetail = (row) => {
  // TODO: 实现查看活动详情
}

// 查看优惠券详情
const handleViewCouponDetail = (row) => {
  // TODO: 实现查看优惠券详情
}

// 分页
const handlePromotionSizeChange = (val) => {
  promotionPage.size = val
  getPromotionList()
}

const handlePromotionCurrentChange = (val) => {
  promotionPage.current = val
  getPromotionList()
}

const handleCouponSizeChange = (val) => {
  couponPage.size = val
  getCouponList()
}

const handleCouponCurrentChange = (val) => {
  couponPage.current = val
  getCouponList()
}

// 查看营销统计
const handleViewStatistics = () => {
  router.push('/merchant/marketing/statistics')
}

onMounted(() => {
  getStatistics()
  getPromotionList()
  getCouponList()
  getLevelList()
  getTagList()
})
</script>

<style lang="scss" scoped>
.marketing-management {
  padding: 20px;

  .statistics-cards {
    margin-bottom: 20px;

    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }

    .card-content {
      text-align: center;

      .amount {
        font-size: 24px;
        font-weight: bold;
        margin-bottom: 10px;
      }

      .trend {
        font-size: 14px;
        color: var(--el-text-color-secondary);

        .up {
          color: var(--el-color-success);
        }

        .down {
          color: var(--el-color-danger);
        }
      }

      .percentage {
        font-size: 14px;
        color: var(--el-text-color-secondary);
      }
    }
  }

  .promotion-card,
  .coupon-card {
    margin-bottom: 20px;

    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
  }

  .pagination {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style> 